"""解析toplog的各进程CPU占用情况，并保存到parse_top.txt"""
import re

with open('toplog', 'r') as f:
    lines = [s.strip() for s in f.readlines()]

process_dict = {}
top_start = False
for line in lines:
    line = re.sub(" +", " ", line)
    if "PID USER" in line and not top_start:
        top_start = True
        continue

    if "-------------------" in line and top_start:
        top_start = False
        continue

    if not top_start:
        continue

    pid_info = line.split(" ")
    if len(pid_info) != 13 and len(pid_info) != 14:
        continue

    command = pid_info[-2]
    if "kworker" in command:
        if "-" in command:
            command = command.split("-")[-1]
        elif "+" in command:
            command = command.split("+")[-1]
        command = "kworker/" + command
    cpu_ocupy = float(pid_info[-5])
    if command in process_dict:
        process_dict[command]["cpu"] += cpu_ocupy
        process_dict[command]["count"] += 1
        if process_dict[command]["cpu_max"] < cpu_ocupy:
            process_dict[command]["cpu_max"] = cpu_ocupy
        if process_dict[command]["cpu_min"] > cpu_ocupy:
            process_dict[command]["cpu_min"] = cpu_ocupy
    else:
        process_dict[command] = {"cpu": cpu_ocupy, "cpu_max": cpu_ocupy, "cpu_min": cpu_ocupy, "count": 1}

process_list = []
for k in process_dict:
    process_dict[k]["cpu_avg"] = round(process_dict[k]["cpu"] / process_dict[k]["count"], 2)
    process_list.append([k, process_dict[k]["cpu_max"], process_dict[k]["cpu_min"], process_dict[k]["cpu_avg"], process_dict[k]["count"]])

process_list.sort(key=lambda x: (x[-2], x[-1]), reverse=True)

save_log = open("parse_top.txt", "w")

save_log.write("command cpu_max cpu_min cpu_avg count\n")
for process in process_list:
    process = list(map(str, process))
    process_info = " ".join(process) + "\n"
    save_log.write(process_info)
    print(process_info, end="")